package com.eastelsoft.smartiot.bssserver.util;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {
	private static final Logger logger = LoggerFactory
			.getLogger(HttpUtils.class);
	private static final int CONNECTION_TIMEOUT = 50000;// http 连接超时
	private static final int SO_TIMEOUT = 25000;// 数据响应超时
	private static final Map<String, String> DEFAULT_REQUEST_PROPERTIES = new HashMap<String, String>();
	static {
		DEFAULT_REQUEST_PROPERTIES.put("Charset", "UTF-8");
		DEFAULT_REQUEST_PROPERTIES.put("Content-type", "application/json");
		DEFAULT_REQUEST_PROPERTIES.put("Connection", "keep-alive");
	}

	public static HttpResp doHttpPost(String url, String body) {
		return doHttpPost(url, DEFAULT_REQUEST_PROPERTIES, body, SO_TIMEOUT);
	}

	public static HttpResp doHttpPost(String url, Map<String, String> params,
			String body) {
		return doHttpPost(url, params, body, SO_TIMEOUT);
	}

	public static HttpResp doHttpPost(String url, Map<String, String> params,
			String body, int readtimeout) {
		HttpURLConnection conn = null;
		HttpResp response = null;
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			logger.info("请求url: {0}, params: {1}, body: {2}", url, params, body);
			if (params != null) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					conn.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setConnectTimeout(CONNECTION_TIMEOUT);
			conn.setReadTimeout(readtimeout);
			conn.setUseCaches(false);
			conn.getOutputStream().write(body.getBytes("utf-8"));
			conn.getOutputStream().flush();
			conn.getOutputStream().close();
			response = doPostResponse(conn, url);
			logger.info("doHttpPost Ok:" + url + ", "
					+ JacksonUtils.beanToJson(response));
		} catch (ConnectException e) {
			logger.error("doHttpPost fail:" + url + " " + e.getMessage());
			return HttpResp.newNetworkError();
		} catch (IOException e) {
			logger.error("doHttpPost fail:" + url + " " + e.getMessage());
			return HttpResp.newNetworkError();
		} catch (Exception e) {
			logger.error("doHttpPost fail:" + url + " " + e.getMessage());
			return HttpResp.newSystemError();
		} finally {
			if (conn != null) {
				try {
					if (conn.getInputStream() != null) {
						conn.getInputStream().close();
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				try {
					if (conn.getErrorStream() != null) {
						conn.getErrorStream().close();
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				conn.disconnect();
			}
		}
		return response;
	}

	private static HttpResp doResponse(HttpURLConnection conn)
			throws IOException {
		int responseCode;
		responseCode = conn.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			return new HttpResp(responseCode, read(conn.getInputStream()));
		} else {
			return new HttpResp(responseCode, "");
		}
	}

	// /**
	// * Get方式请求
	// *
	// * @param reqURl
	// * @return
	// */
	// public static String openGetURL(String reqURl) {
	//
	// HttpURLConnection conn = null;
	// String response = "";
	//
	// try {
	// conn = (HttpURLConnection) new URL(reqURl).openConnection();
	// conn.setRequestMethod("GET");
	// conn.setConnectTimeout(15000);
	// conn.setReadTimeout(30000);
	// response = doGetResponce(conn);
	// } catch (IOException e) {
	// e.printStackTrace();// 网络异常
	// } finally {
	// if (conn != null) {
	// conn.disconnect();
	// }
	// }
	// return response;
	// }

	/**
	 * 返回Post处理
	 * 
	 * @param conn
	 * @return
	 * @throws IOException
	 */
	private static HttpResp doPostResponse(HttpURLConnection conn, String url)
			throws IOException {
		int responseCode;
		responseCode = conn.getResponseCode();
		logger.info(url + " -->reponseCode  " + responseCode);
		if (responseCode == HttpURLConnection.HTTP_OK) {
			return new HttpResp(responseCode, read(conn.getInputStream()));
		} else {
			return new HttpResp(responseCode, "");
		}
	}

	/**
	 * 处理get返回
	 * 
	 * @param conn
	 * @return
	 * @throws IOException
	 */
	// private static String doGetResponce(HttpURLConnection conn)
	// throws IOException {
	// int responseCode;
	// responseCode = conn.getResponseCode();
	// if (responseCode == HttpURLConnection.HTTP_OK) {
	// return read(conn.getInputStream());
	// } else {
	// conn.getInputStream().close();
	// conn.getErrorStream().close();
	// return "";
	// }
	// }

	/**
	 * 将返回的输入流转换成字符串
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	private static String read(InputStream in) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader r = new BufferedReader(new InputStreamReader(in));
		try {
			for (String line = r.readLine(); line != null; line = r.readLine()) {
				sb.append(line);
			}
		} catch (Exception e) {
			logger.error("Exception:",e);
		} finally {
			r.close();
			r = null;
		}
		return sb.toString();
	}

}
